import router from './router'
import { wxConfig } from '@/api/login'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import StoreSave from '@/utils/store'
import { isWeixinCient } from '@/utils/validate'
// import { routeTo } from '@/utils/index'

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/mb/loginRegister/login', '/mb/loginRegister/register', '/mb/errorPage']// no redirect whitelist
const getUid = StoreSave.fetchLocal('uid')

router.beforeEach(async(to, from, next) => {
  // console.log('router.beforeEach...')
  if (getUid || to.query.sid) { // determine if there has token
    /* has token*/
    document.title = to.meta.title
    if (to.path === '/mb/loginRegister/login' || to.path === '/mb/loginRegister/register') {
      const param = {}
      const query = to.query
      param.uri = window.location.href
      param.pid = query.pid
      param.sid = query.sid
      if (param.pid) StoreSave.saveLocal('pid', param.pid)
      if (param.sid) StoreSave.saveLocal('sid', param.sid)
      // alert(param.uri)
      if (!query.sid) { // 微信返回的链接没带上sid
        param.sid = StoreSave.fetchLocal('sid')
      }
      const res = await wxConfig(param)
      if (res.status === 1) {
        if (res.data.is_login == 1) {
          window.location.href = res.data.index_link
        } else {
          next()
        }
      }
      // next({ path: '/mb/dashboard', query: { sid: to.query.sid || 6 }})
      NProgress.done() // 如果是登录页就进首页
    } else {
      if (to.path === '/') {
        // console.log(to.path, '当前路由。。。。')
        // next({ path: '/mb/dashboard', query: { sid: to.query.sid }})
        next()
      } else {
        next()
        // const param = {}
        // const is_not_first = StoreSave.fetch('isNotFirst')
        // if (is_not_first != 1) {
        //   StoreSave.save('isNotFirst', 1)
        // }
        // param.is_not_first = is_not_first ? 1 : 0
        // const query = to.query
        // if (!query.code) {
        //   StoreSave.saveLocal('query', query)
        // }
        // param.uri = window.location.href
        // param.pid = query.pid
        // param.sid = query.sid
        // // param.detailId = query.detailId
        // if (param.pid && param.pid != 'underfind' && param.pid != 0) StoreSave.saveLocal('pid', param.pid)
        // if (param.sid) StoreSave.saveLocal('sid', param.sid)
        // if (!query.sid) { // 微信返回的链接没带上sid
        //   param.sid = StoreSave.fetchLocal('sid')
        // }
        // const res = await wxConfig(param)
        // if (res.status === 1) {
        //   if (res.data && res.data.logo) {
        //     const link = document.querySelector("link[rel*='icon']")
        //     link.href = res.data.logo
        //   }
        //   // console.log(res.data, '配置')
        //   var officialInfo = {}
        //   officialInfo.is_official_account = res.data.is_official_account || ''
        //   officialInfo.account_img = res.data.account_img || ''
        //   officialInfo.account_name = res.data.account_name || ''
        //   officialInfo.must_official_account = res.data.must_official_account || ''
        //   StoreSave.saveLocal('officialInfo', officialInfo)
        //   const appId = res.data.appId
        //   const scope = res.data.scope
        //   const jsapi_url = res.data.jsapi_url
        //   const redirect_uri = encodeURIComponent(res.data.jsapi_url)

        //   if (res.data.is_login === 0 || res.data.current_uid == 0) { // 未登录
        //     const wxUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
        //     if (isWeixinCient()) {
        //       // 微信环境中
        //       // const pid = StoreSave.fetchLocal('pid')
        //       const sid = StoreSave.fetchLocal('sid')
        //       // const uid = Store.fetchLocal('uid')
        //       const queryData = query
        //       if (queryData.code) { // 微信返回的链接
        //         const param = { code: queryData.code }
        //         const resp = await loginByWxcode(param)
        //         if (resp.status === 1) {
        //           const uid = resp.data.uid
        //           if (uid) {
        //             StoreSave.saveLocal('uid', uid)
        //             routeTo(sid, uid)
        //           } else {
        //             next()
        //           }
        //         } else {
        //           location.reload()
        //         }
        //       } else { // 非微信返回的链接，未登录则跳转到微信登录
        //         location.href = wxUrl
        //       }
        //     } else {
        //       next()
        //     }
        //   } else { // 已登录
        //     const uid = res.data.current_uid
        //     StoreSave.saveLocal('uid', uid)
        //     if (query.code && query.state) { // 微信返回的链接
        //       routeTo(param.sid, uid)
        //     } else { // 非微信返回的链接，未登录则跳转到微信登录
        //       if (!query.pid) { // 后台复制的链接没有pid
        //         window.location.href = jsapi_url
        //       } else if (uid !== param.pid) {
        //         if (param.pid != 0) {
        //           // pid不是自己的时候绑定上级
        //           await bindSuperior({ pid: param.pid })
        //           routeTo(param.sid, uid)
        //         } else {
        //           routeTo(param.sid, uid)
        //         }
        //       } else {
        //         next()
        //       }
        //     }
        //   }
        // }
      }
      NProgress.done()
    }
  } else {
    /* has no token*/
    // 如果在微信环境，打开登录注册页跳到首页
    if (isWeixinCient()) {
      if (to.path === '/mb/loginRegister/login' || to.path === '/mb/loginRegister/register') {
        const param = {}
        const query = to.query
        param.uri = window.location.href
        param.pid = query.pid
        param.sid = query.sid
        if (param.pid) StoreSave.saveLocal('pid', param.pid)
        if (param.sid) StoreSave.saveLocal('sid', param.sid)
        // alert(param.uri)
        if (!query.sid) { // 微信返回的链接没带上sid
          param.sid = StoreSave.fetchLocal('sid')
        }
        const res = await wxConfig(param)
        if (res.status === 1) {
          window.location.href = res.data.index_link
        }
      }
    }

    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/mb/loginRegister/login', query: { sid: to.query.sid }}) // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

// 路由出错时
router.onError(error => {
  // console.log(error, '路由错误报告')
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
